package com.dlyk.web;

import com.dlyk.model.Customer;
import com.dlyk.query.CustomerQuery;
import com.dlyk.result.R;
import com.dlyk.service.CustomerService;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;

/**
 * 客户
 */
@RestController
public class CustomerController {

    @Resource
    private CustomerService customerService;

    /**
     * 添加客户（通过线索转换客户）
     */
    @PostMapping("/api/customer/add")
    public R addCustomer(@RequestBody CustomerQuery customerQuery) {

        int save = customerService.saveCustomerByClue(customerQuery);

        // 注意：这里更新了两条数据，返回值应该是2，一条是修改线索状态，一条是添加客户
        return save >= 2 ? R.OK() : R.FAIL();
    }

    /**
     * 获取客户列表（分页查询）
     */
    // 要想使用@PreAuthorize注解，需要在Spring Security配置类中使用@EnableMethodSecurity注解，开启方法级别的权限检查
    // 当前用户有 "customer:list" 这个权限标识符时才可以访问这个控制器
    @PreAuthorize(value = "hasAuthority('customer:list')")
    @GetMapping("/api/customer/list")
    public R customerListByPage(@RequestParam(required = false) Integer current) {

        // required = false  表示非必须，这个参数也可以不传，不传参数，默认查询第一页
        if (current == null) {
            current = 1;
        }

        PageInfo<Customer> customerPageInfo = customerService.getCustomerListByPage(current);

        return R.OK(customerPageInfo);
    }

    /**
     * 导出客户的信息为Excel
     */
    @PreAuthorize(value = "hasAuthority('customer:export')")
    @GetMapping("/api/customer/exportExcel")
    public void exportExcel(HttpServletResponse response,
                            @RequestParam(value = "ids", required = false) List<String> ids) throws IOException {

        // required = false  表示非必须，这个参数也可以不传，不传参数或者传入一个空集合，默认导出所有客户信息Excel
        if (ids == null || ids.isEmpty()) {
            ids = null;
        }

        customerService.exportCustomerListByExcel(response, ids);
    }

    /**
     * 根据id加载客户详情
     */
    @PreAuthorize(value = "hasAuthority('customer:detail')")
    @GetMapping("/api/customer/detail/{id}")
    public R loadCustomerDetail(@PathVariable Integer id) {

        Customer customer = customerService.getCustomerDetailById(id);

        return R.OK(customer);
    }

    /**
     * 编辑客户详细信息
     */
    @PreAuthorize(value = "hasAuthority('customer:edit')")
    @PutMapping("/api/customer/edit")
    public R editCustomer(CustomerQuery customerQuery) {

        int edit = customerService.editCustomer(customerQuery);

        return edit >= 2 ? R.OK() : R.FAIL();
    }

}

